//
//  HWGameCommentSonController.swift
//  HWanGame
//
//  Created by 王昌健 on 2022/3/24.
//  Copyright © 2022 94Wan. All rights reserved.
//

import UIKit
import IQKeyboardManagerSwift
import ZLPhotoBrowser
class HWGameCommentSonController: HWBaseViewController {
    var id = ""
    var gameId = ""
    var ppid = "0"
    var tableView:UITableView!
    var keyboardView:HWGameCommentKeyboardView!
    var tempBgView:UIView!
    let tableViewProtocol = HWGameCommentSonProtocol()
    let httpManager = HWGameDetailHttpManager()
    var replyModel = HWGameDetailCommentListModel()
    var releaseCallBack:(()->())?
    override func viewDidLoad() {
        super.viewDidLoad()
        
        initUI()
        
        initFrame()
        
        loadData()
        
        addAction()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        IQKeyboardManager.shared.enableAutoToolbar = false
        IQKeyboardManager.shared.enable = false
        IQKeyboardManager.shared.shouldToolbarUsesTextFieldTintColor = false
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        IQKeyboardManager.shared.enable = true
        IQKeyboardManager.shared.enableAutoToolbar = true
        IQKeyboardManager.shared.shouldResignOnTouchOutside = false
    }
    
}

extension HWGameCommentSonController {
    private func initUI() -> Void {
        navigationView.titleLabel.text = "评论详情"
        navigationView.backButton.setImage(UIImage(named: "navBackButton"), for: .normal)
        tableView = UITableView.init(frame: CGRect.zero, style: UITableView.Style.plain)
        tableView.delegate = tableViewProtocol
        tableView.dataSource = tableViewProtocol
        tableView.backgroundColor = .colorWithHexString(hexString: "#FFFFFF")
        tableView.separatorStyle = .none
        tableView.rowHeight = UITableView.automaticDimension
        tableView.estimatedRowHeight = 40
        tableView.estimatedSectionHeaderHeight = 0
        tableView.estimatedSectionFooterHeight = 0
        tableView.showsVerticalScrollIndicator = false
        tableView.showsHorizontalScrollIndicator = false
        view.addSubview(tableView)
        tableView.contentInsetAdjustmentBehavior = .never
        tableView.ly_emptyView = LYEmptyView.empty(withImageStr: "", titleStr: "", detailStr: "暂无数据")
        tableView.ly_emptyView.contentViewOffset = -40
        
        tempBgView = UIView.init()
        tempBgView.backgroundColor = UIColor.clear
        tempBgView.isHidden = true
        view.addSubview(tempBgView)
        
        keyboardView = HWGameCommentKeyboardView()
        view.addSubview(keyboardView)
        
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChangeFrameNotify(_:)), name:UIResponder.keyboardWillChangeFrameNotification, object: nil)
        
        let tapBg = UITapGestureRecognizer.init(target: self, action: #selector(closeKeyboard))
        tempBgView.addGestureRecognizer(tapBg)
    }
    
    private func initFrame() -> Void {
        tableView.snp.makeConstraints { make in
            make.top.equalTo(navigationView.snp.bottom)
            make.left.right.equalToSuperview()
            make.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom).offset(-60*widthScale)
        }
        
        tempBgView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        keyboardView.snp.makeConstraints { make in
            make.left.right.equalTo(0)
            make.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom)
        }
    }
}

extension HWGameCommentSonController {
    func loadData() -> Void {
        httpManager.getGameCommentSonList(pid: self.id) { models in
            if models.count > 0 {
                self.navigationView.titleLabel.text = models[0].num + "条回复"
                self.replyModel = models[0]
//                self.replyModel.pid = self.id
//                self.replyModel.ppid = self.id
            }
            self.tableViewProtocol.models = models
            self.tableView.reloadData()
        } failure: { errorString in
            self.view.showHUD(title: errorString)
        }
        
    }
}

extension HWGameCommentSonController {
    func addAction() -> Void {
        tableViewProtocol.zanButtonClick = {
            id in
            self.httpManager.getGameDetailCommentZan(id: id) { success in
                self.loadData()
            } failure: { errorString in
                
            }
        }
        
        tableViewProtocol.videoPlayClick = {
            url in
            
            let vc = ZLImagePreviewController(datas: [URL(string: url)!], index: 0, showSelectBtn: false,showBottomView: false) { (url) -> ZLURLType in
            
                return .video
            } urlImageLoader: { (url, imageView, progress, loadFinish) in
                imageView.kf.setImage(with: url) { (receivedSize, totalSize) in
                    let percentage = (CGFloat(receivedSize) / CGFloat(totalSize))
                    debugPrint("\(percentage)")
                    progress(percentage)
                } completionHandler: { (_) in
                    loadFinish()
                }
            }
            
            vc.doneBlock = { (datas) in
                debugPrint(datas)
            }
            vc.modalPresentationStyle = .fullScreen
            self.showDetailViewController(vc, sender: nil)
        }
        
        tableViewProtocol.replyContent = {
            mod in
            self.replyModel = mod
//            if self.replyModel.id == self.id {
//
//                self.keyboardView.textField.placeholder = "把你想说的写在这里..."
//            }else {
                self.keyboardView.textField.placeholder = "回复：" + mod.user_name
//            }
            
            self.keyboardView.textField.becomeFirstResponder()
        }
        
        keyboardView.sendText = {
            if HWLocallyStoredData.getLoginUserID().count > 0{
                if $0.count > 0 {
                    self.httpManager.sendGameComment(gameId: self.gameId, content: $0, pid: self.replyModel.id, ppid: self.id) { success in
                        self.loadData()
                        self.view.endEditing(true)
                        self.releaseCallBack?()
                    } failure: { errorString in
                        self.view.showHUD(title: errorString)
                    }
                    
                }else{
                    self.view.showHUD(title: "内容不能为空")
                }
            }else{
                let loginController = HWLoginController()
                self.navigationController?.pushViewController(loginController, animated: true)
            }
        }
        
    }
    
    
}

extension HWGameCommentSonController {
    @objc func keyboardWillChangeFrameNotify(_ notify:NSNotification) -> Void {
        let duration = notify.userInfo![UIResponder.keyboardAnimationDurationUserInfoKey] as! Double
        let keyboardFrame = notify.userInfo![UIResponder.keyboardFrameEndUserInfoKey] as! CGRect
        let transformY = keyboardFrame.origin.y - self.view.frame.size.height;
        UIView.animate(withDuration: duration) {
            
            if transformY == 0.0 {
                self.tempBgView.isHidden = true
                self.keyboardView.transform = CGAffineTransform.init(translationX: 0, y: transformY)
                self.keyboardView.textField.placeholder = "请输入评论内容..."
                self.keyboardView.textField.text = ""
                self.replyModel.id = self.id
            }else{
                self.tempBgView.isHidden = false
                if screenHeight < 812 {
                    self.keyboardView.transform = CGAffineTransform.init(translationX: 0, y: transformY)
                    
                }else {
                    self.keyboardView.transform = CGAffineTransform.init(translationX: 0, y: transformY + 34)
                }
                //
            }
            
        }
    }
    
    @objc func closeKeyboard() -> Void {
        view.endEditing(true)
    }
}
